package activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 *消息消费者
 * @Date 2017年10月23日 上午9:19:26
 */
public class JMSConsumer implements MessageListener {

	//默认用户
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	//默认密码
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	//默认连接
	private static final String URL = ActiveMQConnection.DEFAULT_BROKER_URL;
	
	public static void main(String[] args) {
		//连接工厂
		ConnectionFactory connectionFactory;
		//连接
		Connection connection = null;
		//会话 接收或发送消息的线程
		Session session;
		//消息的目的地
		Destination destination;
		//消息的消费者  接收消息者
		MessageConsumer messageConsumer;
		//实例化工厂
		connectionFactory = new ActiveMQConnectionFactory(JMSConsumer.USERNAME, JMSConsumer.PASSWORD, JMSConsumer.URL);
		try {
			//通过连接工厂获取连接
			connection = connectionFactory.createConnection();
			//启动连接
			connection.start();
			//创建session
			session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
			
			//文本消息标识
			Queue queue = session.createQueue("queue.msgText");
			//创建消息消费者
			messageConsumer = session.createConsumer(queue);
			messageConsumer.setMessageListener(new JMSConsumer());
			
			//map标识
			Queue queue1 = session.createQueue("queue.msgMap");
			MessageConsumer consumer = session.createConsumer(queue1);
			consumer.setMessageListener(new JMSConsumer());
			
			//对象标识
			Queue queue2 = session.createQueue("queue.msgObj");
			MessageConsumer consumer1 = session.createConsumer(queue2);
			consumer1.setMessageListener(new JMSConsumer());
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e);
		}
	}


	
	public void onMessage(Message message){
		//接收文本消息
		if (message instanceof TextMessage) {//instanceof 测试它所指向的对象是否是TextMessage类
			TextMessage text = (TextMessage)message;
			try {
				System.out.println("收到queue.msgtext发送消息 ："+text.getText());
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		//接收map消息
		if (message instanceof MapMessage) {
			MapMessage map = (MapMessage) message;
			try {
				System.out.println("收到map消息:"+"姓名："+map.getString("name")+" 性别："+map.getString("sex"));
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		//接收对象消息
		if (message instanceof ObjectMessage) {
			ObjectMessage obj = (ObjectMessage) message;
			try {
				User user = (User) obj.getObject();
				System.out.println("收到消息对象:"+"姓名："+user.getName()   +"性别："+user.getSex());
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
